import { useEffect, useState } from 'react'
import style from './index.module.less'
import { getCaseList } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { PullToRefresh, SpinLoading } from 'antd-mobile'
import { SearchOutline, AddOutline } from 'antd-mobile-icons'
import Item from './components/item'
import PageEmpty from '@components/pageEmpty'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { setList, setVersion } from '@src/redux/reducers/chart'

async function getList (dispatch, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseList())
  setLoading(false)
  if (e === null && d !== null) {
    dispatch(setList(d))
  }
}

function Main () {
  const dispatch = useAppDispatch()
  const version = useAppSelector(state => state.chart.version)
  const list = useAppSelector(state => state.chart.list)
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(true)
  useEffect(() => {
    getList(dispatch, setLoading)
  }, [dispatch, version])
  useEffect(() => {
    let timer
    function loop () {
      dispatch(setVersion(Date.now()))
      timer = setTimeout(() => { loop() }, 10000)
    }
    loop()
    return () => {
      timer && clearTimeout(timer)
    }
  }, [dispatch])
  return (
    <div className={style.container}>
      <div className={style.header}>
        <div className={style.search}>
          <div className={style['search-icon']}><SearchOutline /></div>
          <input placeholder='请输入案号' value={search} onInput={e => { setSearch(e.target.value) }} />
          <button className={style['search-btn']} onClick={() => { }}>搜索</button>
        </div>
      </div>
      <div className={style.body}>
        <div className={style.inner}>
          <PullToRefresh
            onRefresh={async () => {
              await getList(dispatch, setLoading)
            }}>
            <div>
              {loading && list.length === 0 && (
                <div className={style.loading}>
                  <SpinLoading />
                </div>
              )}
              {
                !loading && list.length === 0 && (
                  <PageEmpty />
                )
              }
              <div className={style.list}>
                {
                  list.map((li) => {
                    return <Item key={li.id} data={li} />
                  })
                }
              </div>
            </div>
          </PullToRefresh>
        </div>
      </div>
    </div>
  )
}

export default Main
